var path = require('path'),
  gulp = require("gulp"),
  babel = require("gulp-babel"),
  sass = require("gulp-sass"),
  watch = require("gulp-watch"),
  stripCssComments = require('gulp-strip-css-comments'), //删除注释
  changed = require('gulp-changed'), // 只操作有过修改的文件
  imagemin = require('gulp-imagemin'), // 图片压缩
  pngquant = require('imagemin-pngquant'), // 深度压缩
  livereload = require('gulp-livereload'), // 网页自动刷新（文件变动后即时刷新页面）
  webserver = require('gulp-webserver'), // 本地服务器
  concat = require("gulp-concat"), // 文件合并
  autoprefixer = require('gulp-autoprefixer'), // 自动添加CSS3浏览器前缀
  browserify = require("browserify"),
  source = require('vinyl-source-stream'),
  rename = require('gulp-rename'),
  evtStream = require('event-stream'),
  glob = require('glob'),
  uglify = require('gulp-uglify'), // js压缩
  combiner = require("stream-combiner2"),
  fileinclude = require('gulp-file-include'),
  del = require('del');

/* path config */
var htmlPath = ['src/*.html'],
  stylePath = ['src/css/*.scss', '!src/css/variable.scss'],
  imgPath = ['src/img/*.{png,jpg,gif,svg}'],
  jsPath = ['src/js/*.js'],
  libJs = ['src/lib/*.js'],
  lib = ['src/lib/**/*'];

// 注册任务
gulp.task('concat', function () {
  return combiner.obj([
    gulp.src("src/lib/concat/*.js") // 要合并的文件
    .pipe(concat("libs.js")) // 合并成libs.js
    /* 使用uglify进行压缩 */
    .pipe(uglify())
    .pipe(gulp.dest("dist/lib"))
  ]).on('error', console.error.bind(console));
});

gulp.task('html', function () {
  return combiner.obj([
    gulp.src(htmlPath)
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(changed("dist"))
    .pipe(gulp.dest("dist"))
  ]).on('error', console.error.bind(console));
});
gulp.task('lib', function () {
  return combiner.obj([gulp
    .src(lib)
    .pipe(changed("dist"))
    .pipe(gulp.dest("dist/lib"))
  ]).on("error", console.error.bind(console));
});
gulp.task("babeljs", function () {
  return combiner.obj([gulp
    .src(jsPath)
    .pipe(changed("src/js/temp"))
    .pipe(babel({
      presets: ["es2015"]
    }))
    .pipe(gulp.dest("src/js/temp"))
  ]).on("error", console.error.bind(console));
});

gulp.task('browserify', ['babeljs'], function (done) {
  glob("./src/js/temp/*.js", function (err, files) {
    if (err) done(err);
    var tasks = files.map(function (entry) {
      return browserify({
          entries: [entry]
        })
        .bundle()
        .pipe(source(entry))
        .pipe(rename({
          extname: ".js",
          dirname: "js"
        }))
        .pipe(gulp.dest("dist"));
    });
    evtStream.merge(tasks).on("end", function(){
      done();
      del.sync('src/js/temp');
    });
  })
});

gulp.task('sass', function () {
  return combiner.obj([gulp
    .src(stylePath)
    .pipe(changed("dist/css"))
    .pipe(sass({
      outputStyle: "nested"
    }))
    .on("error", function (err) {
      console.error("Error!", err.message); // 显示错误信息
    })
    // 去掉css注释
    .pipe(stripCssComments())
    // auto prefix
    .pipe(autoprefixer({
      browsers: [
        "last 2 version",
        "safari 5",
        "ie 8",
        "opera 12.1",
        "ios 6",
        "android 4"
      ], // 主流浏览器的最新两个版本
      cascade: true // 是否美化属性值
    }))
    .pipe(gulp.dest("dist/css"))
  ]).on("error", console.error.bind(console));
});
gulp.task('images', function () {
  return combiner
    .obj([gulp
      .src(imgPath)
      .pipe(changed("dist/img"))
      .pipe(imagemin({
        progressive: true, // 无损压缩JPG图片
        svgoPlugins: [{
          removeViewBox: false
        }], // 不移除svg的viewbox属性
        use: [pngquant()] // 使用pngquant插件进行深度压缩
      }))
      .pipe(gulp.dest("dist/img"))
    ]).on("error", console.error.bind(console));
});
gulp.task('clean', function () {
  // del.sync(['dist']);
  del.sync(['dist/**','!dist','!dist/img','!dist/img/**']);
})
gulp.task("webserver", ["html", "sass", "images", 'lib', "browserify"], function () {
  gulp.src("./dist") // 服务器目录（.代表根目录）
    .pipe(
      webserver({
        // 运行gulp-webserver
        livereload: true, // 启用LiveReload
        port: 7080,
        open: false // 服务器启动时自动打开网页
      })
    );
});
// 监听任务
gulp.task("watch", ["webserver"], function () {
  gulp.watch(htmlPath, ["html"]);
  gulp.watch(stylePath, ["sass"]);
  gulp.watch(imgPath, ["images"]);
  gulp.watch(jsPath, ["browserify"]);
  gulp.watch(lib, ["lib"]);
});

// 默认任务
gulp.task("default", ['clean'], function () {
  gulp.start(["watch"]);
});